package io.renren.modules.aic.service.impl;

import io.renren.common.utils.DecimalUtils;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.common.validator.Assert;
import io.renren.modules.aic.dao.BalanceTopupDao;
import io.renren.modules.aic.entity.BalanceDetailEntity;
import io.renren.modules.aic.entity.BalanceTopupEntity;
import io.renren.modules.aic.entity.MemberEntity;
import io.renren.modules.aic.service.BalanceDetailService;
import io.renren.modules.aic.service.BalanceTopupService;
import io.renren.modules.aic.service.MemberService;

import java.util.Date;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

@Service("balanceTopupService")
public class BalanceTopupServiceImpl extends ServiceImpl<BalanceTopupDao, BalanceTopupEntity> implements BalanceTopupService {

	@Autowired
	private MemberService memberService;

	@Autowired
	private BalanceDetailService balanceDetailService;

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		String mobile = (String) params.get("mobile");
		Page<BalanceTopupEntity> page = this.selectPage(new Query<BalanceTopupEntity>(params).getPage(),
				new EntityWrapper<BalanceTopupEntity>().eq(StringUtils.isNotBlank(mobile), "mobile", mobile));

		return new PageUtils(page);
	}

	@Override
	public void save(BalanceTopupEntity balanceTopup) {
		MemberEntity member = memberService.selectOne(new EntityWrapper<MemberEntity>().eq("mobile", balanceTopup.getMobile()));
		Assert.notNull(member, "手机号不存在");

		Date now = new Date();
		balanceTopup.setMemberId(member.getId());
		balanceTopup.setCreateTime(now);
		this.insert(balanceTopup);

		member.setBalance(DecimalUtils.add(member.getBalance(), balanceTopup.getAmount()));
		member.setUpdateTime(now);
		memberService.updateById(member);

		BalanceDetailEntity detail = new BalanceDetailEntity();
		detail.setMemberId(member.getId());
		detail.setBalanceChange(balanceTopup.getAmount());
		detail.setCategory(3);// 奖励
		detail.setCreateTime(now);
		balanceDetailService.insert(detail);
	}

}
